<template>
  <div class="dashboard">
    <!-- 顶部概览卡片 -->
    <div class="overview-cards">
      <div class="card">
        <div class="card-icon total">
          <i class="el-icon-user"></i>
        </div>
        <div class="card-content">
          <h3>{{ overview.totalUsers || 0 }}</h3>
          <p>总用户数</p>
        </div>
      </div>
      <div class="card">
        <div class="card-icon active">
          <i class="el-icon-check"></i>
        </div>
        <div class="card-content">
          <h3>{{ overview.activeUsers || 0 }}</h3>
          <p>活跃用户</p>
        </div>
      </div>
      <div class="card">
        <div class="card-icon today">
          <i class="el-icon-plus"></i>
        </div>
        <div class="card-content">
          <h3>{{ overview.todayNewUsers || 0 }}</h3>
          <p>今日新增</p>
        </div>
      </div>
      <div class="card">
        <div class="card-icon month">
          <i class="el-icon-date"></i>
        </div>
        <div class="card-content">
          <h3>{{ overview.monthNewUsers || 0 }}</h3>
          <p>本月新增</p>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 第一行 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">用户注册趋势</div>
          <div ref="trendChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">地区分布</div>
          <div ref="regionChart" class="chart"></div>
        </div>
      </div>

      <!-- 第二行 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">年龄分布</div>
          <div ref="ageChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">性别统计</div>
          <div ref="genderChart" class="chart"></div>
        </div>
      </div>

      <!-- 第三行 -->
      <div class="chart-row">
        <div class="chart-item">
          <div class="chart-title">账号状态</div>
          <div ref="statusChart" class="chart"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">角色分布</div>
          <div ref="roleChart" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      overview: {},
      charts: {}
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()

    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) chart.dispose()
    })
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.charts.trend = echarts.init(this.$refs.trendChart)
      this.charts.region = echarts.init(this.$refs.regionChart)
      this.charts.age = echarts.init(this.$refs.ageChart)
      this.charts.gender = echarts.init(this.$refs.genderChart)
      this.charts.status = echarts.init(this.$refs.statusChart)
      this.charts.role = echarts.init(this.$refs.roleChart)
    },

    // 加载所有数据
    async loadData() {
      try {
        await Promise.all([
          this.loadOverview(),
          this.loadTrendData(),
          this.loadRegionData(),
          this.loadAgeData(),
          this.loadGenderData(),
          this.loadStatusData(),
          this.loadRoleData()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },

    // 加载概览数据
    async loadOverview() {
      const response = await this.$axios.get('/api/statistics/overview')
      this.overview = response.data
    },

    // 加载注册趋势数据
    async loadTrendData() {
      const response = await this.$axios.get('/api/statistics/trend')
      const data = response.data

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.dates.map(date => date.substring(5)), // 只显示月-日
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '新增用户',
          type: 'line',
          smooth: true,
          data: data.counts,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ]
            }
          }
        }]
      }

      this.charts.trend.setOption(option)
    },

    // 加载地区分布数据
    async loadRegionData() {
      const response = await this.$axios.get('/api/statistics/region')
      const data = response.data.data.slice(0, 10) // 只显示前10个地区

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        series: [{
          name: '用户数',
          type: 'bar',
          data: data.map(item => item.value),
          itemStyle: {
            color: '#67C23A'
          }
        }]
      }

      this.charts.region.setOption(option)
    },

    // 加载年龄分布数据
    async loadAgeData() {
      const response = await this.$axios.get('/api/statistics/age')
      const data = response.data

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.categories
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '用户数',
          type: 'bar',
          data: data.values,
          itemStyle: {
            color: '#E6A23C'
          }
        }]
      }

      this.charts.age.setOption(option)
    },

    // 加载性别统计数据
    async loadGenderData() {
      const response = await this.$axios.get('/api/statistics/gender')
      const data = response.data.data

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '性别分布',
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.charts.gender.setOption(option)
    },

    // 加载状态统计数据
    async loadStatusData() {
      const response = await this.$axios.get('/api/statistics/status')
      const data = response.data.data

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '账号状态',
          type: 'pie',
          radius: ['40%', '70%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.charts.status.setOption(option)
    },

    // 加载角色分布数据
    async loadRoleData() {
      const response = await this.$axios.get('/api/statistics/role')
      const data = response.data.data

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '角色分布',
          type: 'pie',
          radius: '50%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }

      this.charts.role.setOption(option)
    },

    // 处理窗口大小变化
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) chart.resize()
      })
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.card-icon.total { background: #409EFF; }
.card-icon.active { background: #67C23A; }
.card-icon.today { background: #E6A23C; }
.card-icon.month { background: #F56C6C; }

.card-content h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.card-content p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  text-align: center;
}

.chart {
  width: 100%;
  height: 300px;
}

@media (max-width: 1200px) {
  .overview-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .chart-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .overview-cards {
    grid-template-columns: 1fr;
  }
}
</style>